﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace SELinks.SELinksEventAddGroup
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class SELinksEventAddGroup : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                if (properties.ListTitle == "Site Links") // Check if the Item was added in Link List
                {
                    SPItem links = properties.ListItem;
                    string categ = (string)links["Group"]; // Value of the fill in box for the Group field
                    Boolean flag = true;

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite oSiteCollection = new SPSite(properties.SiteId))
                        {
                            SPWeb myWeb = oSiteCollection.OpenWeb(properties.RelativeWebUrl);

                            myWeb.AllowUnsafeUpdates = true;
                            SPList objList = myWeb.Lists["Site Links"];

                            SPFieldChoice choiceField = (SPFieldChoice)objList.Fields["Group"];

                            // Checks if the fill in value is already there in the dropdown list
                            foreach (string choiceName in choiceField.Choices)
                            {
                                if (choiceName.ToLower() == categ.ToLower())
                                    flag = false;
                            }

                            if (flag) // if the fill in value is not there in the dropdown list, add the same
                            {
                                choiceField.Choices.Add(categ);
                                choiceField.Update();
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
           base.ItemAdded(properties);
       }


    }
}
